package cn.cqzaier.pub.api.plugin.base.reqeust.qianxun;

import cn.cqzaier.pub.api.plugin.AbstractRebootBaseReq;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.Map;
import java.util.function.Function;

/**
 * 千寻机器人
 * @param <T>
 * @param <R>
 */
@Slf4j
public class QianxunRequestUtil<T extends QianxunRebootRequest, R> extends AbstractRebootBaseReq {


    public QianxunRequestUtil(String requstUrl) {
        super(requstUrl);
    }

    public R doReq(T t, Function<String,R> function){
        final String wxid = ReflectUtil.getFieldValue(t, "wxid").toString();
        final String reqeustUrl = getRequstUrl() + "/DaenWxHook/httpapi/?wxid=" + wxid;
        log.info("requestPost-url:{}-param:{}", reqeustUrl, JSON.toJSONString(t));
        String s = HttpUtil.post( reqeustUrl, JSON.toJSONString(t));
        if (StringUtils.isBlank(s)){
            setHealth(false);
            return null;
        }
        if (JSONUtil.toBean(s,Map.class).get("code").toString().equals("200")){
            setHealth(true);
        }
        log.info("requestPost:{}", s);
        return function.apply(s);
    }

}
